package com.ht.system.service.impl;

import java.util.Collections;
import java.util.List;

import javax.validation.constraints.NotEmpty;

import com.ht.system.service.IEnterpriseFieldAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ht.common.core.enums.SysNormalDisableEnum;
import com.ht.common.core.enums.UserStatus;
import com.ht.common.core.exception.ServiceException;
import com.ht.common.core.utils.DateUtils;
import com.ht.common.core.utils.SnowflakeIdWorker;
import com.ht.common.core.utils.StringUtils;
import com.ht.common.security.utils.SecurityUtils;
import com.ht.system.domain.EnterpriseInfo;
import com.ht.system.domain.EnterpriseOper;
import com.ht.system.domain.SysUser;
import com.ht.system.mapper.EnterpriseInfoMapper;
import com.ht.system.service.IEnterpriseInfoService;
import com.ht.system.service.IEnterpriseOperService;
import com.ht.system.service.ISysUserService;

/**
 * 企业备案Service业务层处理
 *
 * @author zmx
 * @date 2025-03-22
 */
@Service
public class EnterpriseInfoServiceImpl implements IEnterpriseInfoService
{
	@Autowired
	private IEnterpriseFieldAuthService enterpriseFieldAuthService;
	@Autowired
	private EnterpriseInfoMapper enterpriseInfoMapper;
	@Autowired
    private IEnterpriseOperService enterpriseOperService;
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 查询企业备案
     *
     * @param id 企业备案主键
     * @return 企业备案
     */
    @Override
    public EnterpriseInfo selectEnterpriseInfoById(String id)
    {
        return enterpriseInfoMapper.selectEnterpriseInfoById(id);
    }

    /**
     * 查询企业备案列表
     *
     * @param enterpriseInfo 企业备案
     * @return 企业备案
     */
    @Override
    public List<EnterpriseInfo> selectEnterpriseInfoList(EnterpriseInfo enterpriseInfo)
    {
        return enterpriseInfoMapper.selectEnterpriseInfoList(enterpriseInfo);
    }

    /**
     * 新增企业备案
     *
     * @param enterpriseInfo 企业备案
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int insertEnterpriseInfo(EnterpriseInfo enterpriseInfo)
    {
    	checkRepeat(enterpriseInfo.getEntCode());
    	addEntUser(enterpriseInfo);
    	enterpriseInfo.setId(SnowflakeIdWorker.getUUID());
    	enterpriseInfo.setCreateBy(SecurityUtils.getNickName());
        enterpriseInfo.setCreateTime(DateUtils.getNowDate());
        return enterpriseInfoMapper.insertEnterpriseInfo(enterpriseInfo);
    }



	private void checkRepeat(String entCode) {
		EnterpriseInfo diCheck=enterpriseInfoMapper.selectEnterpriseInfoByEntCode(entCode);
		if(null!=diCheck){
			throw new ServiceException("企业社会信用代码已存在");
		}
	}

	/**
     * 修改企业备案
     *
     * @param enterpriseInfo 企业备案
     * @return 结果
     */
    @Override
    public int updateEnterpriseInfo(EnterpriseInfo enterpriseInfo)
    {
		EnterpriseInfo dbRecord=enterpriseInfoMapper.selectEnterpriseInfoById(enterpriseInfo.getId());
		if(null==dbRecord){
			throw new ServiceException("记录不存在");
		}
		dbRecord.setEntName(enterpriseInfo.getEntName());
		dbRecord.setEntShortName(enterpriseInfo.getEntShortName());
		dbRecord.setLegalPerson(enterpriseInfo.getLegalPerson());
		dbRecord.setLinkman(enterpriseInfo.getLinkman());
		dbRecord.setTelephone(enterpriseInfo.getTelephone());
		dbRecord.setEmail(enterpriseInfo.getEmail());
		dbRecord.setCdqMark(enterpriseInfo.getCdqMark());
		dbRecord.setStatus(enterpriseInfo.getStatus());
		dbRecord.setLicenseImg(enterpriseInfo.getLicenseImg());
		dbRecord.setEntType(enterpriseInfo.getEntType());
		dbRecord.setCustomsData(enterpriseInfo.getCustomsData());
		dbRecord.setAddress(enterpriseInfo.getAddress());
		dbRecord.setUpdateTime(DateUtils.getNowDate());
        return enterpriseInfoMapper.updateEnterpriseInfo(dbRecord);
    }

    /**
     * 批量删除企业备案
     *
     * @param ids 需要删除的企业备案主键
     * @return 结果
     */
    @Override
    public int deleteEnterpriseInfoByIds(@NotEmpty(message="参数不能为空") String[] ids)
    {

    	int delRes=0;
    	for (String id : ids) {
    		delRes+=deleteEnterpriseInfoById(id);
		}
        return delRes;
    }

    /**
     * 删除企业备案信息
     *
     * @param id 企业备案主键
     * @return 结果
     */
    public int deleteEnterpriseInfoById(String id)
    {
        return enterpriseInfoMapper.deleteEnterpriseInfoById(id);
    }



	@Override
	public int addOpre(EnterpriseOper enterpriseOper) {
		EnterpriseInfo epi=selectByEntCode(enterpriseOper.getEntCode());
    	if(null==epi){
    		throw new ServiceException("企业不存在");
    	}
    	if(!SysNormalDisableEnum.OK.getCode().equals(epi.getStatus())){
    		throw new ServiceException("企业处于停用状态，不能添加操作员");
    	}
    	//新建用户账号
    	addOperUser(epi,enterpriseOper);
        enterpriseOper.setCreateTime(DateUtils.getNowDate());
		return enterpriseOperService.insertEnterpriseOper(enterpriseOper);
	}

	@Override
	public EnterpriseInfo selectAllByEntCode(String entCode) {
		EnterpriseInfo ei=	this.selectByEntCode(entCode);
		if(null!=ei){
			ei.setFieldAuthList(enterpriseFieldAuthService.selectByEntCode(entCode));
			ei.setOperList(this.enterpriseOperService.selectByEntCode(entCode));
		}
		return ei;
	}

	@Override
	public EnterpriseInfo selectByEntCode(String entCode) {
		return this.enterpriseInfoMapper.selectEnterpriseInfoByEntCode(entCode);
	}

	@Override
	public List<EnterpriseInfo> findAllEnterprise() {
		List<EnterpriseInfo> list = enterpriseInfoMapper.findAllEnterprise();
		return list;
	}


	/**
	 * 认证审核成功之后才能添加
	 * @param enterpriseInfo
	 */
	private void addEntUser(EnterpriseInfo enterpriseInfo) {
		SysUser su=new SysUser();
    	su.setPassword(SecurityUtils.encryptPassword(enterpriseInfo.getEntCode()));
    	su.setNickName(enterpriseInfo.getEntShortName());
    	//su.setPlatforms(enterpriseOper.getPlatforms());
    	su.setEmail(enterpriseInfo.getEmail());
    	//su.setUserId(enterpriseOper.getUserId());
    	su.setPhonenumber(enterpriseInfo.getTelephone());
    	//su.setDelFlag(enterpriseOper.getDelFlag());
    	su.setUserName(enterpriseInfo.getEntCode());
    	//su.setPostIds(enterpriseOper.getPostIds());
    	//su.setRoles(enterpriseOper.getRoles());
    	//su.setFieldCode(enterpriseOper.getFieldCode());
    	su.setStatus(UserStatus.OK.getCode());
    	//su.setRoleIds(enterpriseOper.getRoleIds());
    	//su.setDeptId(enterpriseOper.getDeptId());
    	su.setEntCode(enterpriseInfo.getEntCode());
    	su.setUserType(enterpriseInfo.getEntType());
    	if(StringUtils.isNotBlank(enterpriseInfo.getPlatformCodes())){
    		su.setPlatforms(StringUtils.stringToList(enterpriseInfo.getPlatformCodes(), ","));
    	}
    	sysUserService.registerUser(su);
	}

	/**
	 * 添加操作员用户
	 * @param epi
	 * @param enterpriseOper
	 */
	private void addOperUser(EnterpriseInfo epi,EnterpriseOper enterpriseOper) {
    	SysUser su=new SysUser();
    	su.setPassword(SecurityUtils.encryptPassword(enterpriseOper.getAccount()));
    	su.setNickName(enterpriseOper.getName());
    	//su.setPlatforms(enterpriseOper.getPlatforms());
    	su.setEmail(enterpriseOper.getEmail());
    	//su.setUserId(enterpriseOper.getUserId());
    	su.setPhonenumber(enterpriseOper.getTelephone());
    	//su.setDelFlag(enterpriseOper.getDelFlag());
    	su.setUserName(enterpriseOper.getAccount());
    	//su.setPostIds(enterpriseOper.getPostIds());
    	//su.setRoles(enterpriseOper.getRoles());
    	su.setFieldCode(epi.getFieldCode());
    	su.setStatus(UserStatus.OK.getCode());
    	//su.setRoleIds(enterpriseOper.getRoleIds());
    	//su.setDeptId(enterpriseOper.getDeptId());
    	su.setEntCode(enterpriseOper.getEntCode());
    	su.setUserType(epi.getEntType());

    	if(StringUtils.isNotBlank(epi.getPlatformCodes())){
    		su.setPlatforms(StringUtils.stringToList(epi.getPlatformCodes(), ","));
    	}
    	sysUserService.registerUser(su);
	}
}
